import type { FetchResponse } from 'ofetch';
import { message } from 'ant-design-vue';
import { useUserStore } from "@/store/user";

export interface ResOptions<T> {
  code: number
  data: T
  msg: string,
  result: T,
  success: boolean
}

/**
 * 定义request response 错误类型
 */
export enum ResponseStatusCodes {
  SUCCESS = 200,
  TOKEN_EXPIRATION = 401,
  ERROR = 500,
}

// 添加防抖变量
let errorMessageTimer: any = null;

/**
 * message全局提示信息
 * @param text
 */
const err = (text: string | undefined) => {
  if (errorMessageTimer) {
    return; // 如果已经有提示在显示，则不重复显示
  }
  message.error(text, 1.5);
  errorMessageTimer = setTimeout(() => {
    errorMessageTimer = null;
  }, 1500); // 1.5秒内不重复显示
};

/**
 * 清除登录信息
 */
const clearLoginInfo = () => {
  const user = useUserStore();
  user.logout()
};

/**
 * 处理请求错误
 * @param response
 */
const handleFail = <T>(
  response: FetchResponse<ResOptions<T>> & FetchResponse<ResponseType>
) => {
  err('网络服务异常，请重新加载或联系客服');
  return Promise.reject(new Error('网络服务异常，请重新加载或联系客服'));
};

/**
 * 处理请求异常
 * @param response
 */
const handleResponse = <T>(
  response: FetchResponse<ResOptions<T>> & FetchResponse<ResponseType>
): any => {
  // 401 token过期，只处理一次
  if (response._data?.code === ResponseStatusCodes.TOKEN_EXPIRATION) {
    clearLoginInfo(); // 清除登录信息只需要执行一次
    err(response._data?.msg);
    return Promise.reject(new Error(response._data?.msg));
  }

  // 其他业务错误
  if (response._data?.code !== ResponseStatusCodes.SUCCESS) {
    err(response._data?.msg);
    return Promise.reject(new Error(response._data?.msg));
  }

  return response._data;
};

export default defineNuxtPlugin(async () => {
  const runtimeConfig = useRuntimeConfig();
  const user = useUserStore();
  let defaultBaseURL: any = ''
  console.log('当前环境是否是server:', process.server)
  if (process.server) {
    // await nextTick()
    defaultBaseURL = runtimeConfig.public.apiBaseUrl
  } else {
    await nextTick()
    defaultBaseURL = runtimeConfig.public.apiBaseUrlPrefix
  }
  const myFetch = $fetch.create({
    // 请求拦截器
    onRequest({ options }) {
      options.baseURL = defaultBaseURL;
      // console.log('请求前缀:', defaultBaseURL);
      options.headers = new Headers(options.headers);
      options.headers.set('X-Requested-With', 'XMLHttpRequest');

      // 如果是FormData类型的数据，不要手动设置Content-type，让浏览器自动设置
      if (!(options.body instanceof FormData)) {
        options.headers.set('Content-type', 'application/json');
      }

      // 设置业务请求头
      if (user.token) {
        options.headers.set('Authorization', user.token);
      }
    },
    // 响应拦截
    onResponse({ response }): any {
      // 只处理HTTP状态非200的情况
      if (response.status !== ResponseStatusCodes.SUCCESS) {
        return handleFail(response);
      }
      // 其他情况统一由handleResponse处理
      return handleResponse(response);
    },
    // 错误处理
    onResponseError({ response }) {
      return handleFail(response);
    }
  });
  return {
    provide: { myFetch }
  };
});